﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;
using SharedComponents;
using OurLeague.Object;

namespace OurLeague
{
    public partial class frmFrontEnd : Form
    {
        /// <summary>
        /// Una lista di liste di oggetti di tipo Control.
        /// Ogni posizione della lista rappresenta un insieme di oggetti grafici
        /// che figurano una "slide" (è assolutamente speculare ad una pagina del
        /// slidesContainer (oggetto TabControl) usato solo in modalità di Design).
        /// </summary>
        List<List<Control>> _slidesControls;

        public frmFrontEnd(int slideIndex)
        {
            Application.UseWaitCursor = true;
            InitializeComponent();
            //Caricamento di _slideControls (potrebbe essere ottimizzato sfruttando metodi
            //per la manipolazione delle collezioni (ndr. che non ho avuto voglia di cercare).
            _slidesControls = new List<List<Control>>();

            foreach(TabPage tpage in tcFrontEnd.TabPages)
            {
                _slidesControls.Add(new List<Control>());
                
                foreach(Control control in tpage.Controls)
                {
                    _slidesControls[_slidesControls.Count - 1].Add(control);
                }
            }
            Size = new Size(800, 615);
            showSlide(slideIndex);
            Application.UseWaitCursor = false;
        }

        private void BtnCalendar_Click(object sender, EventArgs e)
        {
            showSlide(0);
            dgCalendar.AutoGenerateColumns = false;
            dgCalendar.DataSource = Dayweek.Dayweeks;
        }

        /// <summary>
        /// Pulisce il pannello e ci aggiunge tutti i control (componenti grafici) della slide
        /// identificata da un certo indice.
        /// </summary>
        /// <param name="slideIndex">Indice della slide da mostrare.</param>
        public void showSlide(int slideIndex)
        {
            pnlFrontEnd.Controls.Clear();
            pnlFrontEnd.Controls.AddRange(_slidesControls[slideIndex].ToArray());
        }

        private void FrontEndForm_Load(object sender, EventArgs e)
        {
            Team.loadAll();
            Match.loadAll();
            Event.loadAll();

            cmbChooseTeam.DataSource = Team.Teams;

            Team.Teams.ForEach(t => new LeagueTableRecord(t));

            dgRank.AutoGenerateColumns = false;

            Championship.Statistics.Sort();
            dgRank.DataSource = Championship.Statistics;
        }

        private void BtnStatistics_Click(object sender, EventArgs e)
        {
            showSlide(2);
        }

        private void BtnTeam_Click(object sender, EventArgs e)
        {
            showSlide(1);
        }

        private void CmbChooseTeam_SelectedIndexChanged(object sender, EventArgs e)
        {
            Team team = Team.load(cmbChooseTeam.SelectedValue.ToString());
            lblTeamName.Text = team.Name;
            lblCity.Text = team.RegisteredOffice;

            Coach coach = Coach.load(team.CoachId);
            lblCoach.Text = coach.Name + " " + coach.Surname;

            Event.loadAll(cmbChooseTeam.SelectedValue.ToString());

            dgList.AutoGenerateColumns = false;
            dgList.DataSource = team.Players;

            dgScorers.AutoGenerateColumns = false;
            dgScorers.DataSource = Team.load(cmbChooseTeam.SelectedValue.ToString()).getScorerList();

            dgYellowCard.AutoGenerateColumns = false;
            dgYellowCard.DataSource = Team.load(cmbChooseTeam.SelectedValue.ToString()).getYellowCardList();

            dgRedCard.AutoGenerateColumns = false;
            dgRedCard.DataSource = Team.load(cmbChooseTeam.SelectedValue.ToString()).getRedCardList();

            lblGoalScored.Text = Team.load(cmbChooseTeam.SelectedValue.ToString())
                .getScorerList().Sum(s => s.GoalNumber).ToString();

            pcLogo.Image = Util.loadImageFromResources(cmbChooseTeam.Text.ToLower());

            LeagueTableRecord ltr = Championship.Statistics.Find(l => l.TeamName == cmbChooseTeam.Text);
            lblPosition.Text = ltr.Position.ToString();
            lblDrown.Text = ltr.Draw.ToString();
            lblWon.Text = ltr.Win.ToString();
            lblLost.Text = ltr.Lost.ToString();
            lblPlayed.Text = ltr.Played.ToString();
            lblGoalScored.Text = ltr.GoalScored.ToString();
            lblGoalConceded.Text = ltr.GoalTaken.ToString();
            lblScores.Text = ltr.Score.ToString();

        }

        private void msiCalendar_Click(object sender, EventArgs e)
        {
            showSlide(0);
            dgCalendar.AutoGenerateColumns = false;
            Dayweek.loadAll();
            dgCalendar.DataSource = Dayweek.Dayweeks;
        }

        private void msiTeam_Click(object sender, EventArgs e)
        {
            showSlide(1);
            lblTeamName.Text = "";
            lblCity.Text = "";
            lblCoach.Text = "";
            lblGoalScored.Text = "";
            pcLogo.Image = null;
            CmbChooseTeam_SelectedIndexChanged(null, null);
        }

        private void msiStatistics_Click(object sender, EventArgs e)
        {
            showSlide(2);
            dgRank.DataSource = Championship.Statistics;
        }

        private void tcStatistics_SelectedIndexChanged(object sender, EventArgs e)
        {
            //var teamList = MySqlQueryHelper.selectQuery(MySqlManager.Connection, "Teams", null, null);
            switch (tcStatistics.SelectedIndex)
            {
                case 1:
                    {
                        var scorerList = new List<Scorer>();

                        foreach (Team team in Team.Teams)
                        {
                            scorerList.AddRange(team.getScorerList());
                        }

                        dgScorersSt.AutoGenerateColumns = false;
                        dgScorersSt.DataSource = scorerList.OrderByDescending(s => s.GoalNumber).ToList();

                        break;
                    }

                case 2:
                    {
                        var yellowCardList = new List<Booked>();

                        foreach (Team team in Team.Teams)
                        {
                            yellowCardList.AddRange(team.getYellowCardList());
                        }

                        dgYellowCardSt.AutoGenerateColumns = false;
                        dgYellowCardSt.DataSource = yellowCardList.OrderByDescending(b => b.BookingNumber).ToList();

                        break;
                    }
                case 3:
                    {
                        var redCardList = new List<Expelled>();

                        foreach (Team team in Team.Teams)
                        {
                            redCardList.AddRange(team.getRedCardList());
                        }

                        dgRedCardSt.AutoGenerateColumns = false;
                        dgRedCardSt.DataSource = redCardList.OrderByDescending(s => s.ExpelletionNumber).ToList();

                        break;
                    }
                case 4:
                    {
                        var playerPlayTimeList = new List<PlayTime>();

                        foreach (Team team in Team.Teams)
                        {
                            playerPlayTimeList.AddRange(team.getPlayedTimeList());
                        }

                        dgPlayedMinutes.AutoGenerateColumns = false;
                        dgPlayedMinutes.DataSource = playerPlayTimeList.Where(p => p.TimePlayed > 0).ToList()
                            .OrderByDescending(s => s.TimePlayed).ToList();

                        break;
                    }
            }
        }

        private void dgCalendar_SelectionChanged(object sender, EventArgs e)
        {
            if (dgCalendar.RowCount == 0 || dgCalendar.SelectedRows.Count == 0) return;

            var row = dgCalendar.SelectedRows[0];

            var queryResult = Match.loadAll(row.Cells[0].Value.ToString());
            var matchList = new BindingList<Match>(queryResult);
            foreach (Match m in queryResult)
                Event.loadAll(m);

            dgMatches.AutoGenerateColumns = false;
            dgMatches.DataSource = matchList;
            if (matchList.Count == 0)
                dgMatchDetails.DataSource = null;
        }

        private void dgMatches_SelectionChanged(object sender, EventArgs e)
        {            
            lblRefereeName.Text = "";
            if (dgMatches.SelectedRows.Count == 0)
                return;

            var row = dgMatches.SelectedRows[0];
            Match selectedMatch = Match.load(row.Cells[0].Value.ToString());
            Event.loadAll(selectedMatch);


            var localLineUp = selectedMatch.LocalLineUp;
            var guestLineUp = selectedMatch.GuestLineUp;

            localLineUp.RegularPlayers.ForEach(p => p.isRegular = true);
            localLineUp.ReservePlayers.ForEach(p => p.isRegular = false);

            guestLineUp.RegularPlayers.ForEach(p => p.isRegular = true);
            guestLineUp.ReservePlayers.ForEach(p => p.isRegular = false);

            var localPlayerList = new List<Player>(localLineUp.RegularPlayers);
            localPlayerList.AddRange(localLineUp.ReservePlayers);

            var guestPlayerList = new List<Player>(guestLineUp.RegularPlayers);
            guestPlayerList.AddRange(guestLineUp.ReservePlayers);

            dgMatchDetails.AutoGenerateColumns = false;
            dgMatchDetails.DataSource = Event.Events.FindAll(E => E.MatchId == selectedMatch.Id).OrderByDescending(EV => EV.Minute).OrderByDescending(EV => EV.Half).ToList();
            
            dgLocalLineUp.AutoGenerateColumns = false;
            dgLocalLineUp.DataSource = localPlayerList.OrderByDescending(p => p.isRegular).ToList();

            dgGuestLineUp.AutoGenerateColumns = false;
            dgGuestLineUp.DataSource = guestPlayerList.OrderByDescending(p => p.isRegular).ToList();

            pctLocalTeam.Image = Util.loadImageFromResources(localLineUp.TeamName.ToLower() + "_small");
            pctGuestTeam.Image = Util.loadImageFromResources(guestLineUp.TeamName.ToLower() + "_small");

            lblLocalTeam.Text = localLineUp.TeamName;
            lblGuestTeam.Text = guestLineUp.TeamName;
            lblMatchResult.Text = row.Cells[2].Value.ToString();

            var referee = selectedMatch.Referee;
            lblRefereeName.Text = referee.Surname + " " + referee.Name;
        }
    }
}
